package com.unity.bh3.service.impl;

import com.unity.bh3.dto.InventoryItemDTO;
import com.unity.bh3.dto.PurchaseRequest;
import com.unity.bh3.dto.UserCharacterDTO;
import com.unity.bh3.entity.Character;
import com.unity.bh3.entity.UserCharacter;
import com.unity.bh3.entity.UserItem;
import com.unity.bh3.mapper.CharacterMapper;
import com.unity.bh3.mapper.UserCharacterMapper;
import com.unity.bh3.mapper.UserItemMapper;
import com.unity.bh3.service.InventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 背包服务实现类
 */
@Slf4j
@Service
public class InventoryServiceImpl implements InventoryService {
    
    @Autowired
    private UserItemMapper userItemMapper;
    
    @Autowired
    private UserCharacterMapper userCharacterMapper;
    

    
    @Autowired
    private CharacterMapper characterMapper;
    

    
    @Override
    public List<UserCharacterDTO> getUserCharacters(Long userId) {
        log.info("获取用户角色列表，用户ID: {}", userId);
        
        List<UserCharacter> userCharacters = userCharacterMapper.selectUserCharactersWithDetails(userId);
        List<UserCharacterDTO> characterDTOs = new ArrayList<>();
        
        for (UserCharacter userCharacter : userCharacters) {
            UserCharacterDTO dto = new UserCharacterDTO();
            BeanUtils.copyProperties(userCharacter, dto);
            characterDTOs.add(dto);
        }
        
        log.info("用户 {} 拥有 {} 个角色", userId, characterDTOs.size());
        return characterDTOs;
    }
    
    @Override
    public List<Long> getUserCharacterIds(Long userId) {
        log.info("获取用户角色ID列表，用户ID: {}", userId);
        
        List<Long> characterIds = userCharacterMapper.selectCharacterIdsByUserId(userId);
        log.info("用户 {} 拥有角色ID列表: {}", userId, characterIds);
        
        return characterIds;
    }
    

    

    
    @Override
    @Transactional
    public boolean addItemToInventory(Long userId, Long itemId, Integer quantity, Integer itemType) {
        log.info("添加物品到背包（带类型），用户ID: {}, 物品ID: {}, 数量: {}, 类型: {}", userId, itemId, quantity, itemType);
        
        try {
            // 查询用户是否已有该物品
            UserItem existingUserItem = userItemMapper.selectByUserIdAndItemId(userId, itemId);
            
            if (existingUserItem != null) {
                // 更新数量和类型
                existingUserItem.setQuantity(existingUserItem.getQuantity() + quantity);
                existingUserItem.setItemType(itemType);
                existingUserItem.setUpdateTime(new Date());
                userItemMapper.updateById(existingUserItem);
                log.info("更新背包物品数量和类型，用户ID: {}, 物品ID: {}, 新数量: {}, 类型: {}", 
                        userId, itemId, existingUserItem.getQuantity(), itemType);
            } else {
                // 新增物品
                UserItem newUserItem = new UserItem();
                newUserItem.setUserId(userId);
                newUserItem.setItemId(itemId);
                newUserItem.setQuantity(quantity);
                newUserItem.setItemType(itemType);
                newUserItem.setCreateTime(new Date());
                newUserItem.setUpdateTime(new Date());
                userItemMapper.insert(newUserItem);
                log.info("添加新物品到背包（带类型），用户ID: {}, 物品ID: {}, 数量: {}, 类型: {}", userId, itemId, quantity, itemType);
            }
            
            return true;
        } catch (Exception e) {
            log.error("添加物品到背包失败", e);
            return false;
        }
    }
    
    @Override
    public List<Long> getInventoryItemIdsByType(Long userId, Integer itemType) {
        log.info("根据类型获取背包物品ID列表，用户ID: {}, 物品类型: {}", userId, itemType);
        
        try {
            return userItemMapper.selectItemIdsByUserIdAndType(userId, itemType);
        } catch (Exception e) {
            log.error("根据类型获取背包物品ID列表失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    @Transactional
    public boolean addCharacterToUser(Long userId, Long characterId) {
        log.info("添加角色到用户，用户ID: {}, 角色ID: {}", userId, characterId);
        
        try {
            // 检查角色是否存在
            Character character = characterMapper.selectById(characterId);
            if (character == null) {
                log.error("角色不存在，角色ID: {}", characterId);
                return false;
            }
            
            // 检查用户是否已拥有该角色
            UserCharacter existingUserCharacter = userCharacterMapper.selectByUserIdAndCharacterId(userId, characterId);
            if (existingUserCharacter != null) {
                log.warn("用户已拥有该角色，用户ID: {}, 角色ID: {}", userId, characterId);
                return false;
            }
            
            // 添加角色到用户
            UserCharacter newUserCharacter = new UserCharacter();
            newUserCharacter.setUserId(userId);
            newUserCharacter.setCharacterId(characterId);
            newUserCharacter.setLevel(1);
            newUserCharacter.setStar(character.getRarity());
            newUserCharacter.setObtainTime(new Date());
            newUserCharacter.setCreateTime(new Date());
            newUserCharacter.setUpdateTime(new Date());
            
            userCharacterMapper.insert(newUserCharacter);
            log.info("成功添加角色到用户，用户ID: {}, 角色ID: {}", userId, characterId);
            
            return true;
        } catch (Exception e) {
            log.error("添加角色到用户失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean removeItemFromInventory(Long userId, Long itemId, Integer quantity) {
        log.info("删除背包物品，用户ID: {}, 物品ID: {}, 数量: {}", userId, itemId, quantity);
        
        try {
            // 查询用户是否拥有该物品
            UserItem userItem = userItemMapper.selectByUserIdAndItemId(userId, itemId);
            if (userItem == null) {
                log.warn("用户不拥有该物品，用户ID: {}, 物品ID: {}", userId, itemId);
                return false;
            }
            
            // 检查数量是否足够
            if (userItem.getQuantity() < quantity) {
                log.warn("物品数量不足，用户ID: {}, 物品ID: {}, 拥有数量: {}, 删除数量: {}", 
                    userId, itemId, userItem.getQuantity(), quantity);
                return false;
            }
            
            // 更新物品数量
            int newQuantity = userItem.getQuantity() - quantity;
            if (newQuantity == 0) {
                // 如果数量为0，删除记录
                userItemMapper.deleteById(userItem.getId());
                log.info("物品数量为0，删除记录，用户ID: {}, 物品ID: {}", userId, itemId);
            } else {
                // 更新数量
                userItem.setQuantity(newQuantity);
                userItem.setUpdateTime(new Date());
                userItemMapper.updateById(userItem);
                log.info("更新物品数量，用户ID: {}, 物品ID: {}, 新数量: {}", userId, itemId, newQuantity);
            }
            
            return true;
        } catch (Exception e) {
            log.error("删除背包物品失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean removeCharacterFromUser(Long userId, Long characterId) {
        log.info("删除用户角色，用户ID: {}, 角色ID: {}", userId, characterId);
        
        try {
            // 查询用户是否拥有该角色
            UserCharacter userCharacter = userCharacterMapper.selectByUserIdAndCharacterId(userId, characterId);
            if (userCharacter == null) {
                log.warn("用户不拥有该角色，用户ID: {}, 角色ID: {}", userId, characterId);
                return false;
            }
            
            // 删除角色记录
            userCharacterMapper.deleteById(userCharacter.getId());
            log.info("成功删除用户角色，用户ID: {}, 角色ID: {}", userId, characterId);
            
            return true;
        } catch (Exception e) {
            log.error("删除用户角色失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean removeMultipleItemsFromInventory(Long userId, List<Long> itemIds, List<Integer> quantities, Integer itemType) {
        log.info("批量删除背包物品（同一类型），用户ID: {}, 物品ID列表: {}, 数量列表: {}, 物品类型: {}", userId, itemIds, quantities, itemType);
        
        if (itemIds == null || quantities == null || itemIds.size() != quantities.size()) {
            log.warn("参数无效，物品ID列表和数量列表长度不匹配");
            return false;
        }
        
        if (itemType == null || itemType < 1 || itemType > 4) {
            log.warn("物品类型无效: {}", itemType);
            return false;
        }
        
        try {
            for (int i = 0; i < itemIds.size(); i++) {
                Long itemId = itemIds.get(i);
                Integer quantity = quantities.get(i);
                
                if (itemId == null || quantity == null || quantity <= 0) {
                    log.warn("跳过无效的物品删除请求，物品ID: {}, 数量: {}", itemId, quantity);
                    continue;
                }
                
                // 验证物品类型是否匹配
                UserItem userItem = userItemMapper.selectByUserIdAndItemId(userId, itemId);
                if (userItem == null) {
                    log.warn("用户不拥有该物品，用户ID: {}, 物品ID: {}", userId, itemId);
                    continue;
                }
                
                if (!itemType.equals(userItem.getItemType())) {
                    log.warn("物品类型不匹配，期望类型: {}, 实际类型: {}, 物品ID: {}", itemType, userItem.getItemType(), itemId);
                    continue;
                }
                
                // 调用单个删除方法
                boolean success = removeItemFromInventory(userId, itemId, quantity);
                if (!success) {
                    log.warn("删除物品失败，物品ID: {}, 数量: {}", itemId, quantity);
                    // 继续处理其他物品，不中断整个批量操作
                }
            }
            
            log.info("批量删除背包物品完成，用户ID: {}", userId);
            return true;
        } catch (Exception e) {
            log.error("批量删除背包物品失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean removeMultipleCharactersFromUser(Long userId, List<Long> characterIds) {
        log.info("批量删除用户角色，用户ID: {}, 角色ID列表: {}", userId, characterIds);
        
        if (characterIds == null || characterIds.isEmpty()) {
            log.warn("角色ID列表为空");
            return false;
        }
        
        try {
            for (Long characterId : characterIds) {
                if (characterId == null) {
                    log.warn("跳过无效的角色ID: null");
                    continue;
                }
                
                // 调用单个删除方法
                boolean success = removeCharacterFromUser(userId, characterId);
                if (!success) {
                    log.warn("删除角色失败，角色ID: {}", characterId);
                    // 继续处理其他角色，不中断整个批量操作
                }
            }
            
            log.info("批量删除用户角色完成，用户ID: {}", userId);
            return true;
        } catch (Exception e) {
            log.error("批量删除用户角色失败", e);
            return false;
        }
    }
}